﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.Utilities;

namespace Examples.CAMLFilter
{
    class FormEditor : EditorPart
    {
        private Locale locale = new Locale();


        #region Controls

        DropDownList ddlColumns;
        DropDownList ddlMethod;
        CheckBox cbShowConditions;
        CheckBox cbUseCookies;

        TextBox tbWidth;

        #endregion Controls

        // Кастуем папу в нужный тип
        private CAMLFilterForm camlFilterForm
        {
            get { return this.WebPartToEdit as CAMLFilterForm; }
        }

        protected override void CreateChildControls()
        {
            try
            {

                // Описание
                Panel pTitle = new Panel() { CssClass = "UserSectionHead" };
                pTitle.Controls.Add(new Label() { Text = SPUtility.GetLocalizedString("$Resources:WPFDescription", "Examples.CAMLFilter", locale) });
                this.Controls.Add(pTitle);

                this.Controls.Add(new Panel() { CssClass = "UserDottedLine", Width = Unit.Percentage(100) });

                Panel pParams = new Panel() { CssClass = "UserSectionBody" };
                this.Controls.Add(pParams);

                // Количество столбцов
                Panel pColumns = new Panel() { CssClass = "UserControlGroup" };
                pColumns.Controls.Add(new Label() { Text = SPUtility.GetLocalizedString("$Resources:WPFColumns", "Examples.CAMLFilter", locale) + "&nbsp;" });
                ddlColumns = new DropDownList() { ID = "ddlColumns", CssClass = "UserInput" };
                for (int i = 1; i <= 10; i++)
                    ddlColumns.Items.Add(new ListItem(i.ToString()));
                pColumns.Controls.Add(ddlColumns);

                pParams.Controls.Add(pColumns);

                // Ширина текстового поля
                Panel pWidth = new Panel() { CssClass = "UserControlGroup" };
                pWidth.Controls.Add(new Label() { Text = SPUtility.GetLocalizedString("$Resources:WPFWidth", "Examples.CAMLFilter", locale) + "&nbsp;" });
                tbWidth = new TextBox() { ID = "tbWidth", CssClass = "UserInput", Columns = 5 };
                pWidth.Controls.Add(tbWidth);

                CustomValidator regVal = new CustomValidator();
                regVal.ControlToValidate = tbWidth.ID;
                regVal.ServerValidate += new ServerValidateEventHandler(WidthValidator);
                regVal.EnableClientScript = true;
                regVal.Display = ValidatorDisplay.Dynamic;
                regVal.ErrorMessage = "<br/>" + SPUtility.GetLocalizedString("$Resources:WPFErrBadWidth", "Examples.CAMLFilter", locale);
                pWidth.Controls.Add(regVal);

                pParams.Controls.Add(pWidth);


                // Метод передачи параметров
                Panel pMethod = new Panel() { CssClass = "UserControlGroup" };
                pMethod.Controls.Add(new Label() { Text = SPUtility.GetLocalizedString("$Resources:WPFMethod", "Examples.CAMLFilter", locale) + "<br/>" });
                ddlMethod = new DropDownList() { ID = "ddlMethod", CssClass = "UserInput" };
                foreach (ValueSource vs in new List<ValueSource>() { ValueSource.URL, ValueSource.Form })
                    ddlMethod.Items.Add(new ListItem(SPUtility.GetLocalizedString("$Resources:ValueSource" + vs.ToString(), "Examples.CAMLFilter", locale), ((int)vs).ToString()));
                pMethod.Controls.Add(ddlMethod);

                pParams.Controls.Add(pMethod);

                // Показывать подсказки
                Panel pShowConditions = new Panel() { CssClass = "UserControlGroup" };
                cbShowConditions = new CheckBox() { ID = "cbShowConditions", Text = SPUtility.GetLocalizedString("$Resources:WPFShowConditions", "Examples.CAMLFilter", locale), CssClass = "UserInput" };
                pShowConditions.Controls.Add(cbShowConditions);

                pParams.Controls.Add(pShowConditions);

                // Хранить значения в cookies
                Panel pUseCookies = new Panel() { CssClass = "UserControlGroup" };
                cbUseCookies = new CheckBox() { ID = "cbUseCookies", Text = SPUtility.GetLocalizedString("$Resources:WPFUseCookies", "Examples.CAMLFilter", locale), CssClass = "UserInput" };
                pUseCookies.Controls.Add(cbUseCookies);

                pParams.Controls.Add(pUseCookies);



            }
            catch (Exception ex)
            {
                this.Controls.Add(new LiteralControl(String.Format(SPUtility.GetLocalizedString("$Resources:ErrorPrompt", "Examples.CAMLFilter", locale), ex.Message) + "<br/>"));
            }

        }



        // Валидация ширины
        private void WidthValidator(object source, ServerValidateEventArgs args)
        {
            int width = -1;
            args.IsValid = (Int32.TryParse(tbWidth.Text, out width) && width > 50 && width < 1000);
        }


        #region EditorPart abstracts implementation

        public override void SyncChanges()
        {
            EnsureChildControls();

            if (ddlColumns != null && camlFilterForm.FormColumns > 0)
                ddlColumns.SelectedValue = camlFilterForm.FormColumns.ToString();

            if (ddlMethod != null && camlFilterForm.Method > 0)
                ddlMethod.SelectedValue = ((int)camlFilterForm.Method).ToString();

            if (cbShowConditions != null)
                cbShowConditions.Checked = camlFilterForm.ShowConditions;

            if (cbUseCookies != null)
                cbUseCookies.Checked = camlFilterForm.UseCookies;

            if (tbWidth != null)
                tbWidth.Text = camlFilterForm.TextWidth.ToString();

        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();

            camlFilterForm.FormColumns = (ddlColumns != null && !String.IsNullOrEmpty(ddlColumns.SelectedValue)) ? Int32.Parse(ddlColumns.SelectedValue) : 1;

            camlFilterForm.Method = (ddlMethod != null && !String.IsNullOrEmpty(ddlMethod.SelectedValue)) ? (ValueSource)Int32.Parse(ddlMethod.SelectedValue) : ValueSource.URL;

            camlFilterForm.ShowConditions = (cbShowConditions != null ? cbShowConditions.Checked : false);

            camlFilterForm.UseCookies = (cbUseCookies != null ? cbUseCookies.Checked : false);

            int i;
            camlFilterForm.TextWidth = (tbWidth != null && Int32.TryParse(tbWidth.Text, out i)) ? (i < 50 ? 150 :  i) : 150;

            return true;
        }

        #endregion  EditorPart abstracts implementation

    }
}
